package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.enums.SplitMergeEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowStateEnum;
import com.softer.wxzj.common.flow.enums.FlowTypeEnum;
import com.softer.wxzj.common.flow.util.FlowAddAuditUtil;
import com.softer.wxzj.common.flow.util.FlowAuditUtil;
import com.softer.wxzj.common.logic.CalculateAmount;
import com.softer.wxzj.common.util.OperUtil;
import com.softer.wxzj.common.util.ShiroUserUtil;
import com.softer.wxzj.common.util.UUIDUtil;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.SplitMergeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author Gong Zhiyang
 * @date 2019/5/29
 */
@Service
public class SplitMergeServiceImpl implements SplitMergeService {
    @Autowired
    private SplitMergeReqListMapper splitMergeReqListMapper;
    @Autowired
    private SplitMergeReqDetailMapper splitMergeReqDetailMapper;
    @Autowired
    private BaseModifyReqMapper baseModifyReqMapper;
    @Autowired
    private FlowAddAuditUtil flowAddAuditUtil;
    @Autowired
    private BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    private BaseOwnerInfoMapper baseOwnerInfoMapper;
    @Autowired
    private OperUtil zoneCodeUtil;
    @Autowired
    private FlowInstanceMapper flowInstanceMapper;
    @Autowired
    private FlowAuditUtil flowUtil;
    @Autowired
    private BaseOwnerInfoServiceImpl baseOwnerInfoServiceImpl;
    @Autowired
    private CalculateAmount calculateAmount;

    /**
     * 查询房屋合并/拆分审核列表
     *
     * @param page              分页信息
     * @param splitMergeReqList 查询实体
     *                          regionNo 小区编码
     *                          regionName 小区名称
     *                          createTime 申请开始时间
     *                          updateTime 申请结束时间
     *                          creater 申请人
     * @return 查询结果
     */
    @Override
    public PageInfo<SplitMergeReqList> getSplitMergeAuditList(Page page, SplitMergeReqList splitMergeReqList) {
        //查询业务
        Map<String, String> map = flowUtil.getBussIdAndZoneCodeByOperNo(FlowTypeEnum.SPLIT_MERGE.getType());
        List<SplitMergeReqList> list = new ArrayList<>();
        if (map != null) {
            splitMergeReqList.setId(map.get("id"));
            splitMergeReqList.setState(NumberEnum.ONE.getNum());
            //赋值区域,重要
            splitMergeReqList.setZoneCode(zoneCodeUtil.getZoneCode());
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = splitMergeReqListMapper.getSplitMergeAuditList(splitMergeReqList);
        }
        PageInfo<SplitMergeReqList> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 查询房屋合并/拆分详情
     *
     * @param id req_list的Id
     * @return 查询结果
     */
    @Override
    public SplitMerge getSplitMergeReqInfo(String id) {
        SplitMergeReqList splitMergeReqList = splitMergeReqListMapper.selectByPrimaryKey(id);
        SplitMerge splitMerge = new SplitMerge();
        //获取原数据
        List<SplitMergeReqDetail> oldList = splitMergeReqDetailMapper.getSplitMergeReqInfo(id, String.valueOf(NumberEnum.ONE.getNum()));
        if (!checkList(splitMerge, oldList)) {
            return splitMerge;
        }
        //获取新数据
        List<SplitMergeReqDetail> newList = splitMergeReqDetailMapper.getSplitMergeReqInfo(id, String.valueOf(NumberEnum.TWO.getNum()));
        if (!checkList(splitMerge, newList)) {
            return splitMerge;
        }
        if (NumberEnum.ONE.getNum().equals(splitMergeReqList.getType())) {
            //拆分
            splitMerge.setDetail(oldList.get(NumberEnum.ZERO.getNum()));
            splitMerge.setList(newList);
        } else {
            //合并
            splitMerge.setDetail(newList.get(NumberEnum.ZERO.getNum()));
            splitMerge.setList(oldList);
        }
        splitMerge.setType(splitMergeReqList.getType());
        return splitMerge;
    }

    /**
     * 校验查询的集合是否为空
     *
     * @param splitMerge 返回实体
     * @param list       查询的集合
     * @return 检验结果
     */
    private Boolean checkList(SplitMerge splitMerge, List<SplitMergeReqDetail> list) {
        if (list == null || list.size() == NumberEnum.ZERO.getNum()) {
            SplitMergeReqDetail splitMergeReqDetail = new SplitMergeReqDetail();
            splitMerge.setDetail(splitMergeReqDetail);
            splitMerge.setList(new ArrayList<>());
            return false;
        }
        return true;
    }

    /**
     * 房屋合并/拆分审核
     *
     * @param id      审核ID
     * @param opinion 审批意见
     * @param mark    审批通过 audit_pass
     *                审批否决 audit_veto
     *                审批退回 audit_back
     * @return 操作结果
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult audit(String id, String opinion, String mark) {
//        //查询业务id
//        String businessId = baseModifyReqMapper.getBusinessId(id);
//        if (StringUtils.isBlank(businessId)) {
//            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum());
//        }
        //返回审批状态
        String auditState = flowAddAuditUtil.audit(id, opinion, mark,null);
        if (StringUtils.isBlank(auditState)) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(),"审核错误");
        }
        //修改split_merge_req_list表的状态
        int num = splitMergeReqListMapper.updateState(id, auditState, ShiroUserUtil.getUserName());
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //终审成功，修改业务表    其他状态不做处理
        if (FlowStateEnum.PASS.getState().equals(auditState)) {
            //将原数据做逻辑删除，新增新的数据
            dealBusiness(id);
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 房屋合并/拆分
     * TODO 重新整理业务逻辑，后期再处理（包括拆分合并的其他接口）
     *
     * @param splitMerge 拆分/合并实体
     * @return 合并/拆分结果
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult splitMerge(SplitMerge splitMerge) {
        List<SplitMergeReqDetail> list = splitMerge.getList();
        if (list == null || list.size() == NumberEnum.ZERO.getNum()) {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum());
        }
        //新增拆分合并记录ID
        String uuid = UUIDUtil.getUUID();
        if (SplitMergeEnum.SPLIT.getFlag().equals(splitMerge.getType())) {
            //拆分处理
            String houseId = splitMerge.getDetail().getHouseId();
            if (StringUtils.isBlank(houseId)) {
                return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "房屋信息有误");
            }
            //校验房屋是否存在在途业务
            String msg = checkHouseId(houseId);
            if (StringUtils.isNotBlank(msg)) {
                return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), msg);
            }
            dealSplit(splitMerge, uuid);
        } else if (SplitMergeEnum.MERGE.getFlag().equals(splitMerge.getType())) {
            //合并处理
            dealMerge(splitMerge, uuid);
        } else {
            return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "拆分/合并标识错误");
        }
        //新增一条拆分合并记录
        addSplitMergeReqList(splitMerge, uuid);
        //新增一条审批流
        String state = flowAddAuditUtil.initFlow(uuid, FlowTypeEnum.SPLIT_MERGE.getType(), null);
        //当返回通过"2"时 表明该记录不需要审核，直接更新到业务表
        if (FlowStateEnum.PASS.getState().equals(state)) {
            //修改split_merge_req_list表的状态
            int num = splitMergeReqListMapper.updateState(uuid, state, ShiroUserUtil.getUserName());
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "拆分合并失败，稍后请重试");
            }
            //将原数据做逻辑删除，新增新的数据
            dealBusiness(uuid);
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 检查日期是否为空
     * @param detail
     */
    private void checkDate(SplitMergeReqDetail detail){
        if (StringUtils.isEmpty(detail.getPurchaseDate())){
            detail.setPurchaseDate(null);
        }
        if (StringUtils.isEmpty(detail.getContractDate())){
            detail.setContractDate(null);
        }
    }
    /**
     * 校验房屋是否存在在途业务
     *
     * @param houseId 房屋ID
     * @return 结果
     */
    public String checkHouseId(String houseId) {
        //检验审批流中是否存在
        FlowInstance infoByFlowTypeAnBussId = flowInstanceMapper.getInfoByFlowTypeAnBussId(houseId);
        if (infoByFlowTypeAnBussId != null) {
            String id = infoByFlowTypeAnBussId.getId();
            if (StringUtils.isNotBlank(id)) {
                return "该房间存在审批业务";
            }
        }
        //查询是否存在房屋调换在途业务
        String reqId = splitMergeReqListMapper.checkChange(houseId);
        if (StringUtils.isNotBlank(reqId)) {
            return "该房间存在房屋调换在途业务";
        }
        //查询是否存在交存业务
        String depId = splitMergeReqListMapper.checkDep(houseId);
        if (StringUtils.isNotBlank(depId)) {
            return "该房间存在交存在途业务";
        }
        //查询使用中是否存在在途业务
        String expId = splitMergeReqListMapper.checkExpProject(houseId);
        if (StringUtils.isNotBlank(expId)) {
            return "该房间存在使用在途业务";
        }
        //校验拆分合并中是否存在
        String id = splitMergeReqListMapper.checkHouseId(houseId);
        if (StringUtils.isNotBlank(id)) {
            return "该房间存在拆分合并在途业务";
        }
        //校验退款中是否存在在途业务
        String refId = splitMergeReqListMapper.checkRef(houseId);
        if (StringUtils.isNotBlank(refId)) {
            return "该房间存在退款在途业务";
        }
        return "";
    }

    /**
     * 模糊查询房屋合并/拆分审变更查询列表
     *
     * @param page  分页信息
     * @param param 模糊查询参数
     * @return 查询结果
     */
    @Override
    public PageInfo<SplitMergeReqList> getSplitMergeAuditListFuzzy(Page page, String param) {
        SplitMergeReqList splitMergeReqList = new SplitMergeReqList();
        splitMergeReqList.setFuzzyParam(param);
        //赋值区域,重要
        splitMergeReqList.setZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<SplitMergeReqList> list = baseModifyReqMapper.splitMergeAuditFuzzySearch(splitMergeReqList);
        PageInfo<SplitMergeReqList> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 拆分前查询房屋详情
     *
     * @param id 房屋Id
     * @return 详情信息
     */
    @Override
    public BaseOwnerInfoMap getSplitInfo(String id) {
        BaseOwnerInfoMap baseOwnerInfoMap = baseHouseInfoMapper.getHouseAndOwnerInfo(id);
        String houseCity = baseHouseInfoMapper.getHouseCityById(id);
        baseOwnerInfoMap.setHouseCity(houseCity);
        return baseOwnerInfoMap;
    }

    /**
     * 合并前查询房屋详情
     *
     * @param id 合并前房屋ID集合，以“，”分隔
     * @return 详情信息
     */
    @Override
    public List<BaseOwnerInfoMap> getMergeInfo(String id) {
        List<BaseOwnerInfoMap> list = new ArrayList<>();
        if (StringUtils.isNotBlank(id)) {
            String[] split = id.split(",");
            for (int i = 0; i < split.length; i++) {
                String houseId = split[i];
                BaseOwnerInfoMap houseAndOwnerInfo = baseHouseInfoMapper.getHouseAndOwnerInfo(houseId);
                String houseCity = baseHouseInfoMapper.getHouseCityById(houseId);
                houseAndOwnerInfo.setHouseCity(houseCity);
                list.add(houseAndOwnerInfo);
            }
        }
        return list;
    }

    /**
     * 房屋合并/拆分审变更查询列表
     *
     * @param page              分页信息
     * @param splitMergeReqList 查询实体
     *                          regionNo 小区编码
     *                          regionName 小区名称
     *                          createTime 申请开始时间
     *                          updateTime 申请结束时间
     *                          creater 申请人
     * @return 查询结果
     */
    @Override
    public PageInfo<SplitMergeReqList> getSplitMergeList(Page page, SplitMergeReqList splitMergeReqList) {
        //赋值区域,重要
        splitMergeReqList.setZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<SplitMergeReqList> list = splitMergeReqListMapper.getSplitMergeAuditList(splitMergeReqList);
        PageInfo<SplitMergeReqList> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 校验房间是否存在在途业务
     *
     * @param houseId 房间ID
     * @return 业务信息，无在途业务，返回null
     */
    @Override
    public String checkHouseInTrain(String houseId) {
        String msg = checkHouseId(houseId);
        if (StringUtils.isBlank(msg)) {
            return null;
        }
        return msg;
    }


    /**
     * 处理合并
     *
     * @param splitMerge 合并实体
     * @param uuid       合并记录ID
     */
    private void dealMerge(SplitMerge splitMerge, String uuid) {
        //合并后的房间数据
        SplitMergeReqDetail detail = splitMerge.getDetail();
        //合并前的房间数据
        List<SplitMergeReqDetail> list = splitMerge.getList();
        BigDecimal bigDecimal = list.stream().map(SplitMergeReqDetail::getFundBal).reduce(BigDecimal::add).get();
        if (bigDecimal == null || bigDecimal.compareTo(detail.getFundBal()) != 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "合并金额不匹配");
        }
        for (SplitMergeReqDetail splitMergeReqDetail : list) {
            String id = splitMergeReqDetail.getId();
            String msg = checkHouseId(id);
            if (StringUtils.isNotBlank(msg)) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), msg);
            }
            splitMergeReqDetail.setHouseId(id);
            splitMergeReqDetail.setDataType(NumberEnum.ONE.getNum());
            splitMergeReqDetail.setId(UUIDUtil.getUUID());
            splitMergeReqDetail.setReqId(uuid);
            splitMergeReqDetail.setCreater(ShiroUserUtil.getUserName());
            splitMergeReqDetail.setModifier(ShiroUserUtil.getUserName());
            int num = splitMergeReqDetailMapper.insert(splitMergeReqDetail);
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
        SplitMergeReqDetail mergeReqDetail = list.get(NumberEnum.ZERO.getNum());
        //新生成的房屋ID
        String houseId = UUIDUtil.getUUID();
        detail.setHouseId(houseId);
        detail.setReqId(uuid);
        //新增合并后房屋明细
        addHouseSplitMergeDetail(detail, mergeReqDetail, NumberEnum.ZERO.getNum());
        //新增合并后房屋业主信息
        addOwner(detail, houseId);
    }

    /**
     * 新增一条拆分合并记录
     *
     * @param splitMerge 拆分实体
     */
    private void addSplitMergeReqList(SplitMerge splitMerge, String uuid) {
        SplitMergeReqList splitMergeReqList = new SplitMergeReqList();
        splitMergeReqList.setId(uuid);
        splitMergeReqList.setRegionId(splitMerge.getRegionId());
        splitMergeReqList.setState(NumberEnum.ONE.getNum());
        splitMergeReqList.setCreater(ShiroUserUtil.getUser().getOperName());
        splitMergeReqList.setModifier(ShiroUserUtil.getUser().getOperName());
        splitMergeReqList.setType(splitMerge.getType());
        int num = splitMergeReqListMapper.insert(splitMergeReqList);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
    }

    /**
     * 处理拆分
     *
     * @param splitMerge 拆分实体
     */
    private void dealSplit(SplitMerge splitMerge, String uuid) {
        //原始房间数据
        SplitMergeReqDetail detail = splitMerge.getDetail();
        BigDecimal bigDecimal = splitMerge.getList().stream().map(SplitMergeReqDetail::getFundBal).reduce(BigDecimal::add).get();
        if (bigDecimal == null || bigDecimal.compareTo(detail.getFundBal()) != 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "拆分金额不匹配");
        }
        detail.setDataType(NumberEnum.ONE.getNum());
        detail.setHouseId(detail.getId());
        detail.setId(UUIDUtil.getUUID());
        detail.setReqId(uuid);
        int count = splitMergeReqDetailMapper.insert(detail);
        if (count == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //拆分后的房间数据
        List<SplitMergeReqDetail> list = splitMerge.getList();
        // 新增拆分的房间数据到拆分详情表,新增业主数据（为非当前，不可用状态）
        for (int i = 0; i < list.size(); i++) {
            SplitMergeReqDetail splitMergeReqDetail = list.get(i);
            checkDate(splitMergeReqDetail);
            //创建拆分房间的ID
            String houseId = UUIDUtil.getUUID();
            splitMergeReqDetail.setHouseId(houseId);
            splitMergeReqDetail.setReqId(uuid);
            //新增拆分房屋明细
            addHouseSplitMergeDetail(splitMergeReqDetail, detail, i);
            //新增业主
            addOwner(splitMergeReqDetail, houseId);

        }
    }

    /**
     * 新增拆分/合并房屋信息
     *
     * @param splitMergeReqDetail 拆分/合并后房屋信息
     * @param detail              拆分/合并前房屋信息
     */
    private void addHouseSplitMergeDetail(SplitMergeReqDetail splitMergeReqDetail, SplitMergeReqDetail detail, int i) {
        BaseHouseInfo info = baseHouseInfoMapper.getInfo(detail.getHouseId());
        //房屋数据类型 1原数据 2 新生成数据
        splitMergeReqDetail.setDataType(NumberEnum.TWO.getNum());
        splitMergeReqDetail.setBuildNo(info.getBuildNo());
        splitMergeReqDetail.setCellNo(info.getCellNo());
        splitMergeReqDetail.setFloorNo(info.getFloorNo());
        splitMergeReqDetail.setHouseAttr(detail.getHouseAttr());
        splitMergeReqDetail.setHouseUse(info.getHouseUse());
        splitMergeReqDetail.setBankCode(detail.getBankCode());
        splitMergeReqDetail.setState(NumberEnum.ONE.getNum());
        BaseHouseInfo baseHouseInfo = new BaseHouseInfo();
        baseHouseInfo.setPrice(splitMergeReqDetail.getPrice());
        baseHouseInfo.setStruArea(splitMergeReqDetail.getStruArea());
        baseHouseInfo.setFirstMode(splitMergeReqDetail.getFirstMode());
        //初交应缴
        BigDecimal firstDue = calculateAmount.calculateDueAmount(baseHouseInfo);
        splitMergeReqDetail.setFirstDue(firstDue);
        splitMergeReqDetail.setRateDate(detail.getRateDate());
        splitMergeReqDetail.setAtRate(detail.getAtRate());
        splitMergeReqDetail.setAccState(NumberEnum.ONE.getNum());
        splitMergeReqDetail.setCreater(ShiroUserUtil.getUserName());
        splitMergeReqDetail.setModifier(ShiroUserUtil.getUserName());
        splitMergeReqDetail.setPurchaseDate(  "".equals(splitMergeReqDetail.getPurchaseDate()) ? null : splitMergeReqDetail.getPurchaseDate());
        splitMergeReqDetail.setContractDate("".equals(splitMergeReqDetail.getContractDate()) ? null : splitMergeReqDetail.getContractDate());
        splitMergeReqDetail.setId(UUIDUtil.getUUID());
        int num = splitMergeReqDetailMapper.insert(splitMergeReqDetail);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
    }

    /**
     * 生成房间号
     *
     * @param info 房间信息
     * @return 房间号
     */
    private String getRoomNo(BaseHouseInfo info, int num) {
        if (num == NumberEnum.ZERO.getNum()) {
            return info.getRoomNo();
        }
        int no = Integer.parseInt(info.getRoomNo());
        return String.format("%03d", no + num);
    }

    /**
     * 新增业主数据（为非当前，不可用状态）
     *
     * @param splitMergeReqDetail 拆分实体
     * @param houseId             房间Id
     */
    private void addOwner(SplitMergeReqDetail splitMergeReqDetail, String houseId) {
        BaseOwnerInfo baseOwnerInfo = new BaseOwnerInfo();
        baseOwnerInfo.setId(UUIDUtil.getUUID());
        baseOwnerInfo.setAccNo(houseId);
        //添加新业主编号
        String ownerNo = baseOwnerInfoServiceImpl.ownerNo(houseId);
        baseOwnerInfo.setOwnerNo(ownerNo);
        baseOwnerInfo.setCertNo(splitMergeReqDetail.getCertNo());
        baseOwnerInfo.setCertType(splitMergeReqDetail.getCertType());
        baseOwnerInfo.setName(splitMergeReqDetail.getName());
        baseOwnerInfo.setPhone(splitMergeReqDetail.getPhone());
        //设置账户为非当前状态
        baseOwnerInfo.setState(String.valueOf(NumberEnum.ZERO.getNum()));
        //设置账户为业主
        baseOwnerInfo.setInfoType(String.valueOf(NumberEnum.ZERO.getNum()));
        baseOwnerInfo.setCreater(ShiroUserUtil.getUserName());
        baseOwnerInfo.setModifier(ShiroUserUtil.getUserName());
        baseOwnerInfo.setContractDate(splitMergeReqDetail.getContractDate());
        baseOwnerInfo.setFlowState(String.valueOf(NumberEnum.ZERO.getNum()));
        int num = baseOwnerInfoMapper.insert(baseOwnerInfo);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
    }

    /**
     * 处理业务逻辑
     *
     * @param id 申请Id
     */
    private void dealBusiness(String id) {
        List<SplitMergeReqDetail> list = splitMergeReqDetailMapper.getSplitMergeReqDetailList(id);
        if (list == null || list.size() == 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
//        SplitMergeReqDetail detail = list.get(0);
//        //房间号不能重复  单元id+楼层
//        List<String> roomNoList = baseHouseInfoMapper.getRoomNoByCellNoAndFloorNo(detail.getCellNo(), detail.getFloorNo());
//        //获取拆分/合并的RoomNo集合
//        List<String> collect = list.stream().filter(splitMergeReqDetail -> splitMergeReqDetail.getDataType() == 2).map(SplitMergeReqDetail::getRoomNo).collect(Collectors.toList());
//        //处理需要变更房间号的房间
//        dealRoomNo(detail, roomNoList, collect);
        for (SplitMergeReqDetail splitMergeReqDetail : list) {
            if (NumberEnum.ONE.getNum().equals(splitMergeReqDetail.getDataType())) {
                //將原房间变为“销户”
                closeHouse(splitMergeReqDetail.getHouseId());
            } else {
                //新增房间
                splitMergeReqDetail.setCreater(ShiroUserUtil.getUserName());
                splitMergeReqDetail.setModifier(ShiroUserUtil.getUserName());

                int num = baseHouseInfoMapper.insertSplitMerge(splitMergeReqDetail);
                if (num == NumberEnum.ZERO.getNum()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
                //将新增房间的业主信息变为当前可用
                updateOwnerState(splitMergeReqDetail.getHouseId(), String.valueOf(NumberEnum.ONE.getNum()));
            }
        }
    }

    /**
     * 处理需要变更房间号的房间
     *
     * @param detail     房间详情
     * @param roomNoList 原房间号集合
     * @param collect    拆分、合并的房间号集合
     */
    private void dealRoomNo(SplitMergeReqDetail detail, List<String> roomNoList, List<String> collect) {

        //如果原房间集合中 存在 大于 拆分、合并的集合中最小的房间号，则原房间号需要变更，以方便视图排序（大的房间号+拆分/合并集合的长度）
        //顺序排列
        Collections.sort(collect);
        //倒叙排列
        Collections.reverse(roomNoList);
        int num = Integer.parseInt(collect.get(0));
        for (String roomNo : roomNoList) {
            int no = Integer.parseInt(roomNo);
            if (no >= num) {
                SplitMergeReqDetail splitMergeReqDetail = new SplitMergeReqDetail();
                splitMergeReqDetail.setRoomNo(roomNo);
                splitMergeReqDetail.setCellNo(detail.getCellNo());
                splitMergeReqDetail.setFloorNo(detail.getFloorNo());
                //暂时用roomName存放新的roomNo
                splitMergeReqDetail.setNewRoomNo(String.format("%03d", no + collect.size() - 1));
                //将原房间好修改
                baseHouseInfoMapper.updateRoomNo(splitMergeReqDetail);
            }
        }
    }


    /**
     * 销户
     *
     * @param id 房间ID
     */
    public void closeHouse(String id) {
        //將原房间变为“销户”
        int num = baseHouseInfoMapper.updateState(id, ShiroUserUtil.getUserName());
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //将原房间业主改为非当前
        updateOwnerState(id, String.valueOf(NumberEnum.ZERO.getNum()));
    }

    /**
     * 修改业主状态
     *
     * @param id    房间ID
     * @param state 状态（是否当前业主 0 否 1 是）
     */
    public void updateOwnerState(String id, String state) {
        int num = baseOwnerInfoMapper.updateOwnerState(id, state, ShiroUserUtil.getUserName());
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改拆分合并后业主状态错误，请稍后重试");
        }
    }
}
